package com.yuan.blog.service;

import com.yuan.blog.constatns.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class FollowerService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void followerUser(Integer userId, Integer loginUserId) {

        ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
        String followerKey = String.format(RedisKey.USER_FOLLOWER, loginUserId);
        String fansKey = String.format(RedisKey.USER_FANS, userId);

        // 1.先判断是否已进关注过了
        Long rank = stringStringZSetOperations.rank(fansKey, loginUserId.toString());
//        Long rank2 = stringStringZSetOperations.rank(followerKey, userId.toString());
        if (rank == null) {
            // 在关注列表中添加一个人，按照关注时间来排序，所以分数就是关注时间long类型
            stringStringZSetOperations.add(followerKey, userId.toString(), System.currentTimeMillis());

            // 被关注的人也多一个粉丝
            stringStringZSetOperations.add(fansKey, loginUserId.toString(), System.currentTimeMillis());
        } else {
            // 取消关注，粉丝也要少一个
            stringStringZSetOperations.remove(followerKey, userId.toString());
            stringStringZSetOperations.remove(fansKey, loginUserId.toString());
        }
    }

    // 查看关注的人数
    public Long getFollowerCount(Integer userId) {
        String key = String.format(RedisKey.USER_FOLLOWER,userId);
        return stringRedisTemplate.opsForZSet().size(key);
    }

    // 查看粉丝的人数
    public Long getFanCount(Integer userId) {
        String key = String.format(RedisKey.USER_FANS,userId);
        return stringRedisTemplate.opsForZSet().size(key);
    }

    public Boolean isFollowed(Integer loginUserId,Integer userId){
        ZSetOperations<String, String> stringStringZSetOperations = stringRedisTemplate.opsForZSet();
        String followerKey = String.format(RedisKey.USER_FOLLOWER, loginUserId);
        Long rank = stringStringZSetOperations.rank(followerKey, userId.toString());
        return rank != null ;
    }
}
